using System;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.Configuration;

/* OWED */
using OWED.Document;
using OWED.Network;
using OWED.Network.Messages;
using OWED.Network.Messages.General;
using OWED.Network.Messages.Reply;

/// <summary>
/// Class that logs in every page request
/// </summary>
public static class WebLogin {

	/// <summary>
	/// Connect to backend server, using username and password
	/// </summary>
	/// <param name="conn">out parameter of the connection, gets returned back</param>
	/// <param name="username">username</param>
	/// <param name="password">password</param>
	/// <returns>if login was successuful or not</returns>
	public static int C(out Connection conn, String username, String password)
	{
		try {
			// open the web.config file, see which server to connect to and port also
			conn = new Connection(ConfigurationManager.AppSettings["SERVER"], int.Parse(ConfigurationManager.AppSettings["PORT"]));
		} catch (ConnectionException) {
			conn = null;
			return -1; // the backend server is not up
		}

		try {
			OWED.Network.Messages.Login request = new OWED.Network.Messages.Login(new User(username), new Password(password));
			PassFail reply = (PassFail)MessageGet.GetFromXml(conn.Send(request.ToXml()));
			if (!reply.pass) return 0; // username or password was incorrect
			else return 1;
		} catch (ConnectionException) {
			return -2; // backend server died during request
		}
	}
}